// pages/auth/auth.js
var encryp = require('../../assets/js/encryp.js')
var wxRequest = require('../../assets/js/wxRequest.js')
var common = require('../../assets/js/common.js')
var lockjs = require('../../assets/js/database/lock.js')
var base = require('../../assets/js/base.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hiddenmodalput: true,
    token: '',
    randomKey: '',
    sign: '',
    userId: '',
    index1:'',
    authNoteName:'',
    allKeyArray: [],  //钥匙
    keyArray: [],     //钥匙(只包含名字)
    index2: '',
    allEqument: [],     //设备
    equmentArray: [],  //设备(只包含名字)
    index3: '',
    lockArray: [],     //某个设备的锁列表
    endLockArray: [],  //顺序开锁选择的列表
    allUserArray: [], //审批人
    userArray: [],   //审批人(只包含名字)
    index4: '',
    items: [
      { name: '1', value: '顺序开锁', checked: 'true' },
      { name: '0', value: '乱序开锁'}
    ],
    deptArray: [],   //区域数据(包含区)
    array1: [[], []],
    date: "2018-09-01",
    time: "12:01",
  },
  /**
   * 根据用户获取区域
   */
  getDept: function (e) {
    var that = this;
    var simpleObject = {
      id: that.data.userId
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/dept/byUserlist';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        var data = {
          array1: that.data.array1
        };
        //把区域列表设置到piker组件
        data.array1[0].push(res.data.title)
        var children = res.data.children;
        //该用户属于市下
        var flag = common.isArray(children)
        if (flag) {
          //仅设置区的数据(默认用户只属于一个市)
          that.setData({
            deptArray: children
          })
          for (var i = 0; i < children.length; i++) {
            data.array1[1].push(children[i].title);
          }
        } else {
          that.setData({
            deptArray: res.data
          })
        }
        this.setData(data)
      })
  },
  /**
   * 获取名称输入框的内容
   */
  nameInput: function(e){
    var that = this;
    that.setData({
      authNoteName: e.detail.value
    })
  },
  /**
   * 根据当前用户获取钥匙
   */
  getkeyByUser: function (userId, offset) {
    var that = this;
    var simpleObject = {
      id: userId,
      offset: offset,
      limit: getApp().globalData.limit
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/key/getKeyByUser';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        console.log(res.data)
        var array = res.data;
        that.setData({
          allKeyArray: array
        })
        for (var i = 0; i < array.length;i++){
          array[i] = array[i].keyName
        }
        that.setData({
          keyArray: array
        })
      })
  },
  /**
   * 根据区域获取设备
   */
  getEqument: function (deptId) {
    var that = this;
    var simpleObject = {
      id: deptId,
      offset: '0000',
      limit: getApp().globalData.limit
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/equipment/getEquipmentByDept';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        if (res.data == [] || res.data == '') {
          wx.showToast({
            title: '该区域下无设备,请添加后再提交授权',
            icon: 'none',
            duration: 3000
          });
        }
        var array = res.data;
        
        that.setData({
          allEqument: array  //全部设备
        })
        for (var i = 0; i < array.length; i++) {
          array[i] = array[i].equipmentName
        }
        that.setData({
          equmentArray: array,   //只包含设备名称
        })
      })

  },
  /**
   * 根据当前用户获取审批人员
   */
  getCheckUser:function (userId){
    var that = this;
    var simpleObject = {
      id: userId
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/user/getCheckUser';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        console.log(res.data)
        var array = res.data;
        that.setData({
          allUserArray: array
        })
        for (var i = 0; i < array.length; i++) {
          array[i] = array[i].name
        }
        that.setData({
          userArray: array
        })
      })
  },
  /**
   * 根据设备获取锁列表
   */
  getLockByEquement: function (equementId, offset) {
    var that = this;
    var simpleObject = {
      id: equementId,
      offset: offset,
      limit: getApp().globalData.limit
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    //获取锁信息
    var url = getApp().globalData.httpUrl + '/lock/getLockByEquement';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        if (res.data == [] || res.data == '') {
          wx.showToast({
            title: '设备无锁,请添加后再提交授权',
            icon: 'none',
            duration: 3000
          });
        }
        that.setData({
          lockArray: res.data
        })
      })

  },
  /**
   * 表单提交
   */
  inputSubmit: function(){
    var that = this;
    var simpleObject = {
      type: '1',
      name: base.utf16to8(that.data.authNoteName),
      userId: that.data.userId,
      keyCode: that.data.allKeyArray[that.data.index2].keyCode,
      equementId: that.data.allEqument[that.data.index3].id,
      locks: that.data.endLockArray,
      endTime: that.data.date + ' '+that.data.time+':00',
      checkUser: that.data.allUserArray[that.data.index4].id
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    //提交申请
    var url = getApp().globalData.httpUrl + '/authNote/applyNote';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        console.log(res.data)
        if (parseInt(res.data)>=1){
          wx.navigateTo({
            url: '/pages/msg_success/msg_success'
          })
        }
      })
  },

  /**
   * 选择开锁方式
   */
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
  /**
   * 锁具选择  点击左边框
   */
  lockClick1: function(e){
    var that = this;
    var index = parseInt(e.currentTarget.dataset.index)
    var data = {
      endLockArray: that.data.endLockArray,
      lockArray: that.data.lockArray
    };
    data.endLockArray.push(data.lockArray[index])  //添加到右边数组
    data.lockArray.splice(index,1)                 //删除左边数组元素
    this.setData(data)
  },

  // ------------picker改变事件begin---------------
  /**
   * 区域列表滚动事件
   */
  bindPickerChange1: function (e) {
    var that = this;
    console.log('sss'+e.detail.value)
    that.setData({
      index1: e.detail.value
    })
    //选择区域后获取库房数据
    var jsons = that.data.deptArray;
    if (jsons.length) {
      var dept = that.data.deptArray[that.data.index1[1]];
    } else {          //只有一个区，不需要滚动选择
      var dept = that.data.deptArray;
    }
    // that.getHouse(dept.id)
    that.getEqument(dept.id)
    console.log('用户ID'+that.data.userId)
    //获取审批人员
    that.getCheckUser(that.data.userId);
  },
  /**
   * 钥匙滚动
   */
  bindKeyChange:function(e){
    var that = this;
    console.log('kkk'+e.detail.value)
    that.setData({
      index2: e.detail.value
    })
  },
  /**
   * 设备滚动
   */
  bindEquementChange: function (e) {
    var that = this;
    console.log('equement'+e.detail.value)
    that.setData({
      index3: e.detail.value
    })
    console.log('设备IDIDID' + that.data.allEqument[that.data.index3].id)
    // 获取锁列表
    var simpleObject = {
      id: that.data.allEqument[that.data.index3].id,
      offset: '0000',
      limit: getApp().globalData.limit
    };
    that.getLockByEquement(that.data.allEqument[that.data.index3].id,'0000')
    //清除锁具选择信息
    that.setData({
      endLockArray: []
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },
  bindUserChange: function(e){
    var that = this;
    console.log('userPicker' + e.detail.value)
    that.setData({
      index4: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 每个页面都需要先获取缓存中的token和security
    var tokens = wx.getStorageSync('token')
    var randomKey = wx.getStorageSync('randomKey')
    var sign = wx.getStorageSync('sign')
    var id = wx.getStorageSync('id')
    if (tokens && randomKey) {
      that.setData({
        token: tokens,
        randomKey: randomKey,
        sign: sign,
        userId: id
      })
    }
    that.getDept();
    that.getkeyByUser(that.data.userId, that.data.currentPage);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  openAlert: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  modalinput: function () {
  },
  //取消按钮
  cancel: function () {    
    this.setData({      hiddenmodalput: true    });  
    console.log('用户点击取消')
    },  
  //确认    
  confirm: function () {
    this.setData({      hiddenmodalput: true    })  
    console.log('用户点击确认')
  }


})